<template>
  <div class="doctor-list">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1 class="page-title">医生列表</h1>
    </div>

    <!-- 主内容区域 -->
    <div class="content-area">
      <!-- 搜索筛选区域 -->
      <div class="filter-container">
        <div class="filter-form">
          <div class="filter-item">
            <label class="filter-label">关键词</label>
            <el-input
              v-model="searchForm.keyword"
              placeholder="搜索医生姓名、医院名称、专业领域"
              clearable
              size="default"
              class="filter-input"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>

          <div class="filter-item">
            <label class="filter-label">专业领域</label>
            <el-select
              v-model="searchForm.specialty"
              placeholder="选择专业领域"
              clearable
              size="default"
              class="filter-select"
            >
              <el-option
                v-for="specialty in specialtyOptions"
                :key="specialty"
                :label="specialty"
                :value="specialty"
              />
            </el-select>
          </div>

          <div class="filter-item">
            <label class="filter-label">省市区域</label>
            <el-cascader
              v-model="searchForm.regionCascader"
              :options="regionOptions"
              :props="cascaderProps"
              placeholder="请选择省份/城市"
              clearable
              size="default"
              class="filter-cascader"
              @change="handleSearchRegionChange"
            />
          </div>

          <div class="filter-item">
            <label class="filter-label">排序</label>
            <el-select
              v-model="searchForm.sortBy"
              placeholder="排序方式"
              size="default"
              class="filter-select"
            >
              <el-option label="创建时间" value="createTime" />
              <el-option label="浏览量" value="viewCount" />
            </el-select>
          </div>

          <div class="filter-item">
            <label class="filter-label">顺序</label>
            <el-select
              v-model="searchForm.sortOrder"
              placeholder="排序顺序"
              size="default"
              class="filter-select-small"
            >
              <el-option label="降序" value="desc" />
              <el-option label="升序" value="asc" />
            </el-select>
          </div>

          <div class="filter-actions">
            <el-button type="primary" @click="handleSearch" size="default" class="search-btn">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset" size="default" class="reset-btn">
              重置
            </el-button>
          </div>
        </div>
      </div>

      <!-- 数据表格区域 -->
      <div class="table-section">
        <el-table
          v-loading="loading"
          :data="doctorList"
          style="width: 100%"
          height="calc(100vh - 300px)"
          border
          stripe
          @row-click="handleRowClick"
        >
          <el-table-column type="index" label="序号" width="70" min-width="70" />
          
          <el-table-column label="医生信息" width="220" min-width="180" resizable>
            <template #default="{ row }">
              <div class="doctor-info">
                <el-avatar :size="50" :src="row.avatar" class="doctor-avatar">
                  {{ row.name?.charAt(0) }}
                </el-avatar>
                <div class="doctor-details">
                  <div class="doctor-name">{{ row.name }}</div>
                  <div v-if="row.isHot" class="doctor-hot-tag">
                    <el-tag type="danger" size="small">热门</el-tag>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="专业领域" width="200" min-width="120" resizable>
            <template #default="{ row }">
              <div class="doctor-specialties">
                <el-tag
                  v-for="specialty in row.specialties"
                  :key="specialty"
                  size="small"
                  class="specialty-tag"
                >
                  {{ specialty }}
                </el-tag>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="标签" width="250" min-width="150" resizable>
            <template #default="{ row }">
              <div class="doctor-tag">{{ row.tag }}</div>
            </template>
          </el-table-column>

          <el-table-column label="医院信息" width="240" min-width="180" resizable>
            <template #default="{ row }">
              <div v-if="row.hospitalId" class="hospital-info">
                <div class="hospital-name">{{ row.hospitalId.name }}</div>
                <div class="hospital-rating" v-if="row.hospitalId.rating">
                  <el-rate
                    :model-value="row.hospitalId.rating"
                    disabled
                    show-score
                    text-color="#ff9900"
                    :score-template="`${row.hospitalId.rating?.toFixed(1)}`"
                    size="small"
                  />
                </div>
                <el-tag
                  :type="row.hospitalId.category === '公立' ? 'success' : 'info'"
                  size="small"
                >
                  {{ row.hospitalId.category }}
                </el-tag>
              </div>
              <span v-else class="text-muted">未关联医院</span>
            </template>
          </el-table-column>

          <el-table-column label="产品数量" width="110" min-width="90" resizable align="center">
            <template #default="{ row }">
              <el-tag type="info">{{ row.products?.length || 0 }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="浏览量" prop="viewCount" width="100" min-width="80" resizable align="center" />

          <el-table-column label="创建时间" width="180" min-width="120" resizable>
            <template #default="{ row }">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="200" min-width="180" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="default" @click.stop="viewDetail(row)">
                <el-icon><View /></el-icon>
                详情
              </el-button>
              <el-button type="warning" size="default" @click.stop="editDoctor(row)" style="margin-left: 8px;">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.limit"
            :page-sizes="[7, 10, 20, 50]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 医生详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="医生详情"
      width="800px"
      @close="handleDetailClose"
    >
      <div v-if="currentDoctor" class="doctor-detail">
        <div class="detail-header">
          <el-avatar :size="80" :src="currentDoctor.avatar" class="detail-avatar">
            {{ currentDoctor.name?.charAt(0) }}
          </el-avatar>
          <div class="detail-info">
            <h3 class="detail-name">
              {{ currentDoctor.name }}
              <el-tag v-if="currentDoctor.isHot" type="danger">热门医生</el-tag>
            </h3>
            <p class="detail-hospital">{{ currentDoctor.hospital }}</p>
            <p class="detail-location">{{ currentDoctor.province }} {{ currentDoctor.city }}</p>
          </div>
        </div>

        <el-descriptions :column="2" border>
          <el-descriptions-item label="分类">{{ currentDoctor.category }}</el-descriptions-item>
          <el-descriptions-item label="浏览量">{{ currentDoctor.viewCount }}</el-descriptions-item>
          <el-descriptions-item label="专业领域" :span="2">
            <el-tag
              v-for="specialty in currentDoctor.specialties"
              :key="specialty"
              class="specialty-tag"
            >
              {{ specialty }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="医生标签" :span="2">
            {{ currentDoctor.tag }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">
            {{ formatDate(currentDoctor.createTime) }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 关联医院信息 -->
        <div v-if="currentDoctor.hospitalId" class="hospital-section">
          <h4>关联医院信息</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="医院名称">{{ currentDoctor.hospitalId.name }}</el-descriptions-item>
            <el-descriptions-item label="医院分类">
              <el-tag :type="currentDoctor.hospitalId.category === '公立' ? 'success' : 'info'">
                {{ currentDoctor.hospitalId.category }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="医院评分">
              <el-rate
                v-if="currentDoctor.hospitalId.rating"
                :model-value="currentDoctor.hospitalId.rating"
                disabled
                show-score
                text-color="#ff9900"
                :score-template="`${currentDoctor.hospitalId.rating?.toFixed(1)}`"
              />
              <span v-else>暂无评分</span>
            </el-descriptions-item>
            <el-descriptions-item label="医院状态">
              <el-tag :type="currentDoctor.hospitalId.status === 'active' ? 'success' : 'danger'">
                {{ currentDoctor.hospitalId.status === 'active' ? '启用' : '禁用' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="医院地址" :span="2">
              {{ currentDoctor.hospitalId.location }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 医生产品列表 -->
        <div v-if="currentDoctor.products && currentDoctor.products.length > 0" class="products-section">
          <h4>相关产品 ({{ currentDoctor.products.length }})</h4>
          <div class="products-grid">
            <div
              v-for="product in currentDoctor.products"
              :key="product.id"
              class="product-card"
            >
              <img :src="product.image" :alt="product.title" class="product-image" />
              <div class="product-info">
                <div class="product-title">{{ product.title }}</div>
                <div class="product-price">
                  <span class="current-price">¥{{ product.price }}</span>
                  <span v-if="product.saved" class="saved-price">省¥{{ product.saved }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 编辑医生对话框 -->
    <el-dialog
      v-model="editVisible"
      title="编辑医生信息"
      width="800px"
      @close="handleEditClose"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="120px"
        class="edit-form"
      >
        <!-- 医生头像上传 -->
        <el-form-item label="医生头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :action="uploadAction"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="uploadHeaders"
          >
            <img v-if="editForm.avatar" :src="editForm.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="医生姓名" prop="name">
              <el-input v-model="editForm.name" placeholder="请输入医生姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属医院" prop="hospital">
              <el-select
                v-model="editForm.hospital"
                placeholder="请选择所属医院"
                filterable
                clearable
                style="width: 100%"
                @change="handleHospitalChange"
              >
                <el-option
                  v-for="hospital in hospitals"
                  :key="hospital._id"
                  :label="hospital.name"
                  :value="hospital.name"
                >
                  <div class="hospital-option">
                    <span class="hospital-name">{{ hospital.name }}</span>
                    <span class="hospital-info">{{ hospital.city }} · {{ hospital.category }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="省市区域" prop="regionCascader">
          <el-cascader
            v-model="editForm.regionCascader"
            :options="regionOptions"
            :props="cascaderProps"
            placeholder="请选择省份/城市"
            style="width: 100%"
            @change="handleRegionChange"
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="医生分类" prop="category">
              <el-select v-model="editForm.category" placeholder="请选择医生分类">
                <el-option
                  v-for="category in categories"
                  :key="category"
                  :label="category"
                  :value="category"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否热门">
              <el-switch v-model="editForm.isHot" />
            </el-form-item>
          </el-col>
        </el-row>


        <el-form-item label="专业领域" prop="specialties">
          <el-select
            v-model="editForm.specialties"
            multiple
            filterable
            allow-create
            placeholder="请选择或输入专业领域（最多2个）"
            style="width: 100%"
            @change="handleSpecialtyChange"
          >
            <el-option
              v-for="specialty in specialtyOptions"
              :key="specialty"
              :label="specialty"
              :value="specialty"
            />
          </el-select>
          <div v-if="editForm.specialties.length >= 2" class="specialty-limit-tip">
            <el-text type="warning" size="small">
              已选择 {{ editForm.specialties.length }}/2 个专业领域
            </el-text>
          </div>
        </el-form-item>

        <el-form-item label="医生标签" prop="tag">
          <el-input
            v-model="editForm.tag"
            type="textarea"
            :rows="3"
            placeholder="请输入医生标签描述"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveEdit" :loading="saveLoading">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Search, 
  View,
  Edit,
  Plus
} from '@element-plus/icons-vue'
import request from '@/utils/request'
import { useUserStore } from '@/stores/user'
import { provinceAndCityData } from 'element-china-area-data'

// 接口类型定义
interface Doctor {
  _id: string
  name: string
  hospital: string
  hospitalId?: {
    _id: string
    name: string
    logo?: string
    rating?: number
    location?: string
    category?: string
    status?: string
  }
  avatar?: string
  specialties: string[]
  tag?: string
  category?: string
  city?: string
  province?: string
  isHot: boolean
  viewCount: number
  createTime: string
  products?: Array<{
    id: string
    image?: string
    title: string
    price: number
    saved?: number
  }>
}

interface Pagination {
  current: number
  limit: number
  total: number
  totalPages: number
  hasNextPage: boolean
  hasPrevPage: boolean
}

// 响应式数据
const loading = ref(false)
const doctorList = ref<Doctor[]>([])
const categories = ref<string[]>([])
const hospitals = ref<any[]>([])
const detailVisible = ref(false)
const currentDoctor = ref<Doctor | null>(null)
const editVisible = ref(false)
const editFormRef = ref()
const saveLoading = ref(false)

// 用户store
const userStore = useUserStore()

// 上传配置
const uploadAction = ref(`${import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000'}/pcdoctor/upload-avatar`) // 上传接口地址
const uploadHeaders = ref({
  'Authorization': `Bearer ${userStore.accessToken || ''}`
})

// 编辑表单
const editForm = reactive({
  _id: '',
  name: '',
  hospital: '',
  hospitalId: '', // 医院ID
  province: '',
  city: '',
  regionCascader: [] as string[], // 级联选择器的值
  category: '',
  avatar: '',
  specialties: [] as string[],
  tag: '',
  isHot: false
})

// 专业领域选项（从后端API获取）
const specialtyOptions = ref<string[]>([])

// 编辑表单验证规则
const editRules = {
  name: [
    { required: true, message: '请输入医生姓名', trigger: 'blur' }
  ],
  hospital: [
    { required: true, message: '请输入所属医院名称', trigger: 'blur' }
  ],
  regionCascader: [
    { required: true, message: '请选择省份和城市', trigger: 'change' }
  ],
  category: [
    { required: true, message: '请选择医生分类', trigger: 'change' }
  ],
  specialties: [
    { required: true, message: '请选择专业领域', trigger: 'change' },
    { 
      validator: (_rule: any, value: string[], callback: any) => {
        if (value && value.length > 2) {
          callback(new Error('最多只能选择2个专业领域'))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ]
}

// 搜索表单
const searchForm = reactive({
  keyword: '',
  specialty: '',
  regionCascader: [] as string[], // 省市级联选择器的值
  city: '',
  province: '',
  sortBy: 'createTime',
  sortOrder: 'desc'
})

// 分页信息
const pagination = reactive<Pagination>({
  current: 1,
  limit: 7,
  total: 0,
  totalPages: 0,
  hasNextPage: false,
  hasPrevPage: false
})

// 级联选择器配置
const cascaderProps = {
  value: 'value',
  label: 'label',
  children: 'children'
}

// 省市数据
const regionOptions = ref(provinceAndCityData)

// 方法
const fetchDoctors = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      limit: pagination.limit,
      keyword: searchForm.keyword,
      specialty: searchForm.specialty,
      city: searchForm.city,
      province: searchForm.province,
      sortBy: searchForm.sortBy,
      sortOrder: searchForm.sortOrder
    }

    // 移除空值参数
    Object.keys(params).forEach((key: string) => {
      const paramKey = key as keyof typeof params
      if (params[paramKey] === '' || params[paramKey] === null || params[paramKey] === undefined) {
        delete params[paramKey]
      }
    })

    // 打印调试信息
    console.log('发送给后端的参数:', params)

    const response = await request.get('/pcdoctor/list', { params }) as any
    
    if (response.success) {
      doctorList.value = response.data.doctors
      Object.assign(pagination, response.data.pagination)
    } else {
      ElMessage.error(response.message || '获取医生列表失败')
    }
  } catch (error) {
    console.error('获取医生列表失败:', error)
    ElMessage.error('获取医生列表失败')
  } finally {
    loading.value = false
  }
}

const fetchCategories = async () => {
  try {
    const response = await request.get('/pcdoctor/categories') as any
    if (response.success) {
      categories.value = response.data
    }
  } catch (error) {
    console.error('获取分类失败:', error)
  }
}


const fetchHospitals = async () => {
  try {
    const response = await request.get('/pcdoctor/hospitals') as any
    if (response.success) {
      hospitals.value = response.data
    }
  } catch (error) {
    console.error('获取医院列表失败:', error)
  }
}

const fetchSpecialties = async () => {
  try {
    const response = await request.get('/pcdoctor/specialties') as any
    if (response.success) {
      specialtyOptions.value = response.data
    }
  } catch (error) {
    console.error('获取专业领域选项失败:', error)
  }
}

const fetchDoctorDetail = async (id: string) => {
  try {
    const response = await request.get(`/pcdoctor/detail/${id}`) as any
    if (response.success) {
      currentDoctor.value = response.data
      detailVisible.value = true
    } else {
      ElMessage.error(response.message || '获取医生详情失败')
    }
  } catch (error) {
    console.error('获取医生详情失败:', error)
    ElMessage.error('获取医生详情失败')
  }
}

// 事件处理
const handleSearch = () => {
  pagination.current = 1
  fetchDoctors()
}

const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    specialty: '',
    regionCascader: [],
    city: '',
    province: '',
    sortBy: 'createTime',
    sortOrder: 'desc'
  })
  pagination.current = 1
  fetchDoctors()
}

const handleSearchRegionChange = (value: string | string[]) => {
  if (!value || (Array.isArray(value) && value.length === 0)) {
    searchForm.city = ''
    searchForm.province = ''
    // 清空选择后也要触发搜索
    handleSearch()
    return
  }

  // 处理数组格式的值（完整路径）
  if (Array.isArray(value) && value.length >= 2) {
    const [provinceValue, cityValue] = value
    
    // 根据省份和城市代码找到对应的名称
    for (const province of regionOptions.value) {
      if (province.value === provinceValue && province.children) {
        searchForm.province = province.label
        for (const city of province.children) {
          if (city.value === cityValue) {
            searchForm.city = city.label
            break
          }
        }
        break
      }
    }
  } else if (Array.isArray(value) && value.length === 1) {
    // 只选择了省份
    const [provinceValue] = value
    for (const province of regionOptions.value) {
      if (province.value === provinceValue) {
        searchForm.province = province.label
        searchForm.city = ''
        break
      }
    }
  }
  
  // 打印调试信息
  console.log('省市筛选变更:', {
    province: searchForm.province,
    city: searchForm.city,
    regionCascader: searchForm.regionCascader
  })
  
  // 自动触发搜索
  handleSearch()
}

const handleRegionChange = (value: string | string[]) => {
  if (!value || (Array.isArray(value) && value.length === 0)) {
    editForm.city = ''
    editForm.province = ''
    return
  }

  // 处理数组格式的值（完整路径）
  if (Array.isArray(value) && value.length >= 2) {
    const [provinceValue, cityValue] = value
    
    // 根据省份和城市代码找到对应的名称
    for (const province of regionOptions.value) {
      if (province.value === provinceValue && province.children) {
        editForm.province = province.label
        for (const city of province.children) {
          if (city.value === cityValue) {
            editForm.city = city.label
            break
          }
        }
        break
      }
    }
  }
}

const handleHospitalChange = (hospitalName: string) => {
  // 当选择医院时，自动填充医院所在的省份和城市，并保存医院ID
  const selectedHospital = hospitals.value.find(h => h.name === hospitalName)
  if (selectedHospital) {
    // 保存医院ID
    editForm.hospitalId = selectedHospital._id
    
    // 自动填充省份和城市
    if (selectedHospital.province && selectedHospital.city) {
      // 找到对应的省市级联值
      for (const province of regionOptions.value) {
        if (province.label === selectedHospital.province && province.children) {
          for (const city of province.children) {
            if (city.label === selectedHospital.city) {
              editForm.regionCascader = [province.value, city.value]
              editForm.province = selectedHospital.province
              editForm.city = selectedHospital.city
              break
            }
          }
          break
        }
      }
    }
  } else {
    // 如果没有找到医院，清空医院ID
    editForm.hospitalId = ''
  }
}

const handleSpecialtyChange = (value: string[]) => {
  // 限制专业领域最多选择2个
  if (value.length > 2) {
    ElMessage.warning('最多只能选择2个专业领域')
    // 保留前2个选择的项目
    editForm.specialties = value.slice(0, 2)
  }
}

const handleSizeChange = (val: number) => {
  pagination.limit = val
  pagination.current = 1
  fetchDoctors()
}

const handleCurrentChange = (val: number) => {
  pagination.current = val
  fetchDoctors()
}

const handleRowClick = (row: Doctor) => {
  viewDetail(row)
}

const viewDetail = (row: Doctor) => {
  fetchDoctorDetail(row._id)
}

const handleDetailClose = () => {
  currentDoctor.value = null
}

// 编辑相关方法
const editDoctor = (row: Doctor) => {
  // 填充编辑表单
  Object.assign(editForm, {
    _id: row._id,
    name: row.name,
    hospital: row.hospital,
    hospitalId: row.hospitalId?._id || '', // 设置医院ID
    province: row.province || '',
    city: row.city || '',
    regionCascader: [],
    category: row.category || '',
    avatar: row.avatar || '',
    specialties: [...(row.specialties || [])],
    tag: row.tag || '',
    isHot: row.isHot
  })
  
  // 设置级联选择器的值
  if (row.province && row.city) {
    for (const province of regionOptions.value) {
      if (province.label === row.province && province.children) {
        for (const city of province.children) {
          if (city.label === row.city) {
            editForm.regionCascader = [province.value, city.value]
            break
          }
        }
        break
      }
    }
  }
  
  editVisible.value = true
}

const handleEditClose = () => {
  editVisible.value = false
  // 重置表单
  Object.assign(editForm, {
    _id: '',
    name: '',
    hospital: '',
    hospitalId: '', // 重置医院ID
    province: '',
    city: '',
    regionCascader: [],
    category: '',
    avatar: '',
    specialties: [],
    tag: '',
    isHot: false
  })
  editFormRef.value?.clearValidate()
}


const handleSaveEdit = async () => {
  if (!editFormRef.value) return
  
  try {
    const valid = await editFormRef.value.validate()
    if (!valid) return
    
    saveLoading.value = true
    
    const updateData = {
      name: editForm.name,
      hospital: editForm.hospital,
      hospitalId: editForm.hospitalId, // 包含医院ID
      province: editForm.province,
      city: editForm.city,
      category: editForm.category,
      avatar: editForm.avatar,
      specialties: editForm.specialties,
      tag: editForm.tag,
      isHot: editForm.isHot
    }
    
    const response = await request.put(`/pcdoctor/update/${editForm._id}`, updateData) as any
    
    if (response.success) {
      ElMessage.success('医生信息更新成功')
      editVisible.value = false
      handleEditClose()
      fetchDoctors() // 刷新列表
    } else {
      ElMessage.error(response.message || '更新失败')
    }
  } catch (error) {
    console.error('更新医生信息失败:', error)
    ElMessage.error('更新医生信息失败')
  } finally {
    saveLoading.value = false
  }
}

// 上传相关方法
const handleAvatarSuccess = (response: any) => {
  if (response.success) {
    editForm.avatar = response.data.url
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error(response.message || '头像上传失败')
  }
}

const beforeAvatarUpload = (file: any) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPGOrPNG) {
    ElMessage.error('头像图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!')
    return false
  }
  
  // 更新上传头部信息，确保token是最新的
  if (userStore.accessToken) {
    uploadHeaders.value.Authorization = `Bearer ${userStore.accessToken}`
  }
  
  return true
}

const formatDate = (dateStr: string) => {
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  fetchDoctors()
  fetchCategories()
  fetchHospitals()
  fetchSpecialties()
})
</script>

<style lang="scss" scoped>
.doctor-list {
  .page-header {
    margin-bottom: 24px;

    .page-title {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
      color: #333;
    }
  }

  .content-area {
    background: #fff;
    border-radius: 8px;
    padding: 16px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    height: calc(100vh - 160px); /* 减去页面头部和外边距 */
  }

  /* 筛选容器样式 */
  .filter-container {
    flex-shrink: 0;
    margin-bottom: 16px;
    padding: 16px;
    background: #ffffff;
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);
  }

  .filter-form {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    align-items: center;
  }

  .filter-item {
    display: flex;
    flex-direction: row;
    align-items: center;
    gap: 8px;
  }

  .filter-label {
    color: #606266;
    font-weight: 500;
    white-space: nowrap;
    min-width: 70px;
    text-align: right;
    font-size: 14px;
    flex-shrink: 0;
  }

  .filter-input {
    width: 260px;
    height: 32px;
  }

  .filter-select {
    width: 150px;
    height: 32px;
  }

  .filter-select-small {
    width: 100px;
    height: 32px;
  }

  .filter-cascader {
    width: 240px;
    height: 32px;
  }

  .filter-actions {
    display: flex;
    gap: 8px;
    align-items: center;
  }

  .search-btn, .reset-btn {
    height: 32px;
    padding: 0 16px;
  }

  .table-section {
    flex: 1;
    overflow: hidden;
    
    :deep(.el-table) {
      font-size: 14px;
      
      .el-table__header th {
        font-size: 14px;
        font-weight: 600;
      }
      
      .el-table__body td {
        font-size: 14px;
      }
    }
    
    .doctor-info {
      display: flex;
      align-items: center;
      gap: 12px;

      .doctor-avatar {
        flex-shrink: 0;
      }

      .doctor-details {
        flex: 1;
        min-width: 0;

        .doctor-name {
          font-weight: 600;
          margin-bottom: 6px;
          font-size: 15px;
          color: #333;
        }

        .doctor-hot-tag {
          margin-bottom: 4px;
        }

        .doctor-specialties {
          margin-top: 4px;
          
          .specialty-tag {
            margin-right: 4px;
            margin-bottom: 4px;
          }
        }
      }
    }


    .doctor-tag {
      font-size: 13px;
      color: #666;
      line-height: 1.4;
    }

    .hospital-info {
      .hospital-name {
        font-weight: 500;
        margin-bottom: 4px;
        font-size: 14px;
      }

      .hospital-rating {
        margin-bottom: 4px;
      }
    }

    .text-muted {
      color: #999;
    }

    .pagination-wrapper {
      margin-top: 24px;
      display: flex;
      justify-content: flex-end;
      
      :deep(.el-pagination) {
        font-size: 14px;
      }
    }
  }

  .doctor-detail {
    .detail-header {
      display: flex;
      align-items: center;
      gap: 20px;
      margin-bottom: 24px;
      padding-bottom: 20px;
      border-bottom: 1px solid #eee;

      .detail-avatar {
        flex-shrink: 0;
      }

      .detail-info {
        flex: 1;

        .detail-name {
          margin: 0 0 8px 0;
          display: flex;
          align-items: center;
          gap: 8px;
        }

        .detail-hospital {
          margin: 0 0 4px 0;
          color: #666;
          font-size: 16px;
        }

        .detail-location {
          margin: 0;
          color: #999;
          font-size: 14px;
        }
      }
    }

    .hospital-section {
      margin-top: 24px;

      h4 {
        margin-bottom: 16px;
        color: #333;
      }
    }

    .products-section {
      margin-top: 24px;

      h4 {
        margin-bottom: 16px;
        color: #333;
      }

      .products-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        gap: 16px;

        .product-card {
          border: 1px solid #eee;
          border-radius: 8px;
          overflow: hidden;
          transition: box-shadow 0.2s;

          &:hover {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
          }

          .product-image {
            width: 100%;
            height: 120px;
            object-fit: cover;
          }

          .product-info {
            padding: 12px;

            .product-title {
              font-size: 14px;
              font-weight: 500;
              margin-bottom: 8px;
              color: #333;
              display: -webkit-box;
              -webkit-line-clamp: 2;
              line-clamp: 2;
              -webkit-box-orient: vertical;
              overflow: hidden;
            }

            .product-price {
              display: flex;
              align-items: center;
              gap: 8px;

              .current-price {
                font-size: 16px;
                font-weight: 600;
                color: #ff4d4f;
              }

              .saved-price {
                font-size: 12px;
                color: #52c41a;
              }
            }
          }
        }
      }
    }

    .specialty-tag {
      margin-right: 8px;
      margin-bottom: 8px;
    }
  }

  .edit-form {
    .el-form-item {
      margin-bottom: 20px;
    }

    .el-select {
      width: 100%;
    }

    .hospital-option {
      display: flex;
      flex-direction: column;
      gap: 2px;

      .hospital-name {
        font-weight: 500;
        color: #333;
      }

      .hospital-info {
        font-size: 12px;
        color: #999;
      }
    }

    .specialty-limit-tip {
      margin-top: 4px;
    }

    .avatar-uploader {
      :deep(.el-upload) {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
        width: 120px;
        height: 120px;
        display: flex;
        align-items: center;
        justify-content: center;

        &:hover {
          border-color: var(--el-color-primary);
        }
      }

      .avatar {
        width: 120px;
        height: 120px;
        display: block;
        object-fit: cover;
        border-radius: 6px;
      }

      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        text-align: center;
      }
    }
  }

  .dialog-footer {
    text-align: right;
  }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .filter-form {
    gap: 12px;
  }
  
  .filter-input {
    width: 200px;
    height: 32px;
  }
  
  .filter-select {
    width: 130px;
    height: 32px;
  }
  
  .filter-select-small {
    width: 90px;
    height: 32px;
  }
  
  .filter-cascader {
    width: 200px;
    height: 32px;
  }
}

@media (max-width: 768px) {
  .filter-container {
    padding: 12px;
  }
  
  .filter-form {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .filter-item {
    width: 100%;
  }
  
  .filter-input,
  .filter-select,
  .filter-select-small,
  .filter-cascader {
    width: 100%;
    height: 32px;
  }
  
  .search-btn, .reset-btn {
    height: 32px;
    padding: 0 16px;
  }
}

:deep(.el-table__row) {
  cursor: pointer;

  &:hover {
    background-color: #f5f7fa;
  }
}
</style>